package com.cino.demos.sourceCode.easyexcellike;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping
public class ExcelExportController {

    // 1. 定义数据模型（内部类）
    public static class SimpleData {
        private final String name;
        private final int value;
        // 构造方法
        public SimpleData(String name, int value) {
            this.name = name;
            this.value = value;
        }
        // Getter
        public String getName() { return name; }
        public int getValue() { return value; }
    }

    // 2. Excel导出接口
    @GetMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 模拟数据
        List<SimpleData> dataList = Arrays.asList(
            new SimpleData("A", 10),
            new SimpleData("B", 20)
        );

        // 3. 创建Excel工作簿（内存中）
        try (Workbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            
            Sheet sheet = workbook.createSheet("Data");
            
            // 4. 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("名称");
            headerRow.createCell(1).setCellValue("数值");
            
            // 5. 填充数据
            int rowIdx = 1;
            for (SimpleData data : dataList) {
                Row row = sheet.createRow(rowIdx++);
                row.createCell(0).setCellValue(data.getName());
                row.createCell(1).setCellValue(data.getValue());
            }
            
            // 6. 设置响应头（关键！）
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, 
                "attachment; filename=\"export_data.xlsx\"");
            
            // 7. 流式写入响应
            workbook.write(out);
            response.getOutputStream().write(out.toByteArray());
            response.flushBuffer();
        }
    }



    @GetMapping("/download/txt")
    public void downloadTxt(HttpServletResponse response) throws IOException {
        // 动态生成文本内容（支持换行和中文）
        String content = "动态生成的TXT内容\n时间：" + LocalDateTime.now() + "\n作者：张三";

        // 设置响应头（关键！）
        response.setContentType("text/plain; charset=UTF-8"); // MIME类型 + 编码
        response.setCharacterEncoding("UTF-8"); // 强制指定编码
        response.setHeader("Content-Disposition",
                "attachment; filename=\"dynamic-content.txt\"");

        // 写入响应流
        try (PrintWriter writer = response.getWriter()) {
            writer.write(content);
        } // 自动关闭流
    }
}